#!/bin/bash
set -e  # 出现错误立即退出

REGISTRATION_TOKEN='sqa_4fb14d4be609dcd45a3cc1dcac5550e2652f908d'
DOCKER_VERSION='26.1.4'

get_local_ip() {
  # 尝试多种方法获取本机IP
  local ip
  ip=$(hostname -I 2>/dev/null | awk '{print $1}') || \
  ip=$(ip route get 1 | awk '{print $7; exit}' 2>/dev/null) || \
  ip=$(ifconfig | grep -Eo 'inet (addr:)?([0-9]*\.){3}[0-9]*' | grep -Eo '([0-9]*\.){3}[0-9]*' | grep -v '127.0.0.1' | head -n 1)

  echo "$ip"
}

# 尝试获取公网IP（带超时）
PUBLIC_IP=$(curl -s --max-time 3 ifconfig.me 2>/dev/null || echo "")

if [ -n "$PUBLIC_IP" ]; then
  GITLAB_URL=$PUBLIC_IP
else
  # 获取本机IP地址
  LOCAL_IP=$(get_local_ip)
  if [ -n "$LOCAL_IP" ]; then
    GITLAB_URL=$LOCAL_IP
    echo "警告: 使用本机IP地址: $LOCAL_IP"
  else
    # 无法获取任何IP地址，退出安装
    echo "错误: 无法获取本机IP地址"
    echo "请手动设置 PRIVATE_REGISTRY 环境变量"
    echo "例如: export PRIVATE_REGISTRY='192.168.0.2'"
    exit 1
  fi
fi
# 注册Runner
echo "正在注册Runner..."
REGISTER_OUTPUT=$(docker exec gitlab-runner gitlab-runner register \
  --non-interactive \
  --url "${GITLAB_URL}" \
  --registration-token "${REGISTRATION_TOKEN}" \
  --executor "docker" \
  --docker-image "docker:${DOCKER_VERSION}" \
  --description "Auto-Registered Runner" \
  --tag-list "android,ios,java" \
  --run-untagged \
  --locked=false \
  --docker-privileged=true \
  --docker-volumes "/var/run/docker.sock:/var/run/docker.sock" \
  --docker-volumes "/certs/client" \
  --docker-volumes "/cache" \
  --docker-pull-policy="if-not-present" 2>&1)

echo "$REGISTER_OUTPUT"

# 检查注册结果
if ! echo "$REGISTER_OUTPUT" | grep -q "Runner registered successfully"; then
  echo "错误: Runner注册失败，尝试强制注册..."
  docker exec gitlab-runner gitlab-runner unregister --name "Auto-Registered Runner" 2>/dev/null || true
  docker exec gitlab-runner gitlab-runner register \
    --non-interactive \
    --url "${GITLAB_URL}" \
    --registration-token "${REGISTRATION_TOKEN}" \
    --executor "docker" \
    --docker-image "docker:${DOCKER_VERSION}" \
    --description "Auto-Registered Runner" \
    --tag-list "android,ios,java" \
    --run-untagged \
    --locked=false \
    --docker-privileged=true \
    --docker-volumes "/var/run/docker.sock:/var/run/docker.sock" \
    --docker-volumes "/certs/client" \
    --docker-volumes "/cache" \
    --docker-pull-policy="if-not-present"
fi